package demo.spring.securing.login;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;

/**
 * Created by lushun.chen on 2017/4/17.
 *
 * @author lushun.chen
 */
@Controller
public class CheckCode {

    @RequestMapping("/images/imagecode")
    public String imageCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OutputStream os = response.getOutputStream();
        Map<String, Object> map = ValidateCode.getImageCode(60, 20, os);
        String simleCaptcha = "simleCaptcha";
        request.getSession().setAttribute(simleCaptcha, map.get("strEnsure").toString().toLowerCase());
        request.getSession().setAttribute("codeTime", new Date().getTime());
        ImageIO.write((BufferedImage) map.get("image"), "JPEG", os);
        return null;
    }

    @RequestMapping
    @ResponseBody
    public String checkCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String checkCode = request.getParameter("checkCode");
        Object cko = session.getAttribute("");
        if (cko == null) {
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "验证码已失效，请重新输入！";
        }
        String captcha = cko.toString();
        Date now = new Date();
        Long codeTime = Long.valueOf(session.getAttribute("codeTime") + "");

        if (org.springframework.util.StringUtils.isEmpty(checkCode) || captcha == null || !(checkCode.equalsIgnoreCase(captcha))) {
            request.setAttribute("errorMsg", "验证码错误");
        } else if ((now.getTime() - codeTime) / 1000 / 60 > 5) {
            request.setAttribute("errprMsg", "验证码已经失效，请重新输入");
            return "验证码已经失效，请重新输入";
        } else {
            session.removeAttribute("simleCaptcha");
            return "1";
        }

        return null;
    }
}
